package com.gy.paidao.person;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.TextView;

import com.example.mapdemo.MainActivity;
import com.gy.paidao.BaseActivity;
import com.gy.paidao.MyApplication;
import com.example.mapdemo.R;

import com.gy.paidao.bean.BaseBean;
import com.gy.paidao.person.bean.LoginBean;
import com.gy.paidao.util.AnimUtil;
import com.gy.paidao.util.LogUtil;
import com.gy.paidao.util.ParseBase;
import com.gy.paidao.util.SPHelper;
import com.gy.paidao.util.Urls;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.internal.http.OkHeaders;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.List;
import java.util.Map;

/**
 * 作者：gy on 16/2/17
 * 说明：登录
 */
public class LoginActivity extends BaseActivity{

    private EditText etName,etPassword;
    private TextView tvLogin,tvForger,tvRegister;
    private String strName,strPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        setViews();
    }

    @Override
    protected void initVariable() {

    }

    @Override
    protected void setTitleViews() {

    }

    @Override
    protected void setViews() {
        etName = (EditText) findViewById(R.id.activity_login_et_name);
        etPassword = (EditText) findViewById(R.id.activity_login_et_password);
        tvLogin = (TextView) findViewById(R.id.activity_login_tv_login);
        tvRegister = (TextView) findViewById(R.id.activity_login_tv_register);
        tvForger = (TextView) findViewById(R.id.activity_login_tv_forget);

        tvLogin.setOnClickListener(this);
        tvRegister.setOnClickListener(this);
        tvForger.setOnClickListener(this);
    }

    @Override
    protected void doClickAction(int viewId) {
        super.doClickAction(viewId);
        switch (viewId){
            case R.id.activity_login_tv_login:
                strName = etName.getText().toString().trim();
                strPassword = etPassword.getText().toString().trim();
                if(TextUtils.isEmpty(strName) || TextUtils.isEmpty(strPassword)){
                    showToast(R.string.activity_login_input_error);
                } else {
                    requestLogin();
                }
                break;
            case R.id.activity_login_tv_forget:
                intent = new Intent(this,ForgetActivity.class);
                startActivity(intent);
                AnimUtil.pushLeftInAndOut(this);
                break;
            case R.id.activity_login_tv_register:
                intent = new Intent(this,RegisterActivity.class);
                startActivityForResult(intent,101);
                AnimUtil.pushLeftInAndOut(this);
                break;
        }
    }

    private void requestLogin(){
        showLoading();
        final OkHttpClient client = new OkHttpClient();
        client.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER));
        FormEncodingBuilder builder = new FormEncodingBuilder();
        builder.add("account",strName+"");
        builder.add("password",strPassword+"");
        final Request request = new Request.Builder()
                .url(Urls.url_login)
                .post(builder.build())
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

            }

            @Override
            public void onResponse(final Response response) throws IOException {
                CookieHandler cookieHandler = client.getCookieHandler();
                if (cookieHandler != null) {
                    Map<String, List<String>> headers = OkHeaders.toMultimap(request.headers(), null);
                    Map<String, List<String>> cookies = cookieHandler.get(request.uri(), headers);
                    for (String key : cookies.keySet()) {
                        String cookie = cookies.get(key).get(0);
                        if(cookie.indexOf("userLoginID=") != -1){
                            cookie = cookie.substring(12,cookie.length());
                            LogUtil.e("cookie="+cookie);
                            SPHelper.getInstance(LoginActivity.this).setStringData("userLoginID",cookie);
                        }
                    }
                }

                BaseBean baseBean = ParseBase.parseBase(response);
                if (baseBean.success) {
                    String data = String.valueOf(baseBean.data);
                    LoginBean bean = gson.fromJson(data,LoginBean.class);
                    MyApplication.loginBean = bean;
                    MyApplication.USERID = bean.id;
                    intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                    AnimUtil.pushLeftInAndOut(LoginActivity.this);
                    LoginActivity.this.finish();
                } else {
                    if("0010006".equals(baseBean.errCode)){
                        String data = String.valueOf(baseBean.data);
                        try {
                            JSONObject obj = new JSONObject(data);
                            int userId = obj.optInt("userId");
                            intent = new Intent(LoginActivity.this,RegisterEmailActivity.class);
                            intent.putExtra("userId",userId);
                            intent.putExtra("email",strName);
                            startActivity(intent);
                            AnimUtil.pushLeftInAndOut(LoginActivity.this);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    if(!TextUtils.isEmpty(baseBean.errMsg)){
                        Message msg = new Message();
                        msg.what = 0;
                        msg.obj = baseBean.errMsg;
                        toastHandler.sendMessage(msg);
                    }
                }
            }
        });
    }

    private Handler toastHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String toast = (String) msg.obj;
            showToast(toast);
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 101){
            this.finish();
        }
    }
}
